package com.jiazhong.mingxing.project.bookstore.front.interceptor;

import com.jiazhong.mingxing.project.bookstore.commons.config.JwtConfig;
import com.jiazhong.mingxing.project.bookstore.commons.util.JsonResult;
import com.jiazhong.mingxing.project.bookstore.commons.util.ResultTool;
import com.jiazhong.mingxing.project.bookstore.front.service.impl.UserServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.util.Objects;

@Component
@Slf4j
public class IsLoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取到token
        String token = request.getHeader("token");
        // 2. 判断token是否篡改
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JsonResult fail = ResultTool.fail("请登录后访问", 401);
            out.println(fail);
            return false;
        }
        // 3. 获取redis中存放的token
        Object id = JwtConfig.parseJWT(token).get("id");
        String redisToken = stringRedisTemplate.opsForValue().get(UserServiceImpl.FRONT_TOKEN + id.toString());
        // 4. 比较redis的token和送过来的token
        boolean equals = Objects.equals(redisToken, token);
        if (!equals) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JsonResult fail = ResultTool.fail("请登录后访问", 401);
            out.println(fail);
            return false;
        }
        return true;
    }

}
